package com.example.conexion;



import java.util.Timer;
import java.util.TimerTask;


import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.Handler.Callback;
import android.os.RemoteException;
import android.util.Log;

import android.widget.Toast;

public class monitorAlarma extends Service implements Callback{
	
	public static final int MENSAJE = 1;
	private Messenger servicio;
	private Timer timer=new Timer();
	private static final long UPDATE_INTERVAL=5000;
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		
		servicio = new Messenger(new Handler(this));
		pollForUptates();
		
		Toast.makeText(this, "Servicio creado", Toast.LENGTH_LONG).show();
		Log.d("SERVICEBOOT", "Servicio creado");
		
	}
	
private void pollForUptates(){
	timer.scheduleAtFixedRate(new TimerTask(){
		@Override
		public void run(){
			
			comprobarAlarma comprobar=new comprobarAlarma("1","1");
			estadoAlarma estado=new estadoAlarma();
			estado=comprobar.comprobar();
			Message m = new Message();
			if(estado.getEstado()){
			m.what = 1;
			m.obj=estado;
			}
			else{
				m.what = 0;	
			}
		

				try {
					servicio.send(m);
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
		}
		},0,UPDATE_INTERVAL);
	Log.i(getClass().getSimpleName(),"Inicio consultas");
	}
	

	@Override
	public void onDestroy() {
		super.onDestroy();
		
		Toast.makeText(this, "Servicio destruido", Toast.LENGTH_LONG).show();
		Log.d("SERVICEBOOT", "Servicio destruido");
	}

	@Override
	public boolean handleMessage(Message msg) {
		
		if(msg.what==1){
			estadoAlarma estado=new estadoAlarma();
			estado=(estadoAlarma) msg.obj;
			Intent i = new Intent(monitorAlarma.this, alarma3.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			i.putExtra("idAlarma", Integer.parseInt(estado.getIdAlarma()));
			i.putExtra("tipoAlarma", Integer.parseInt(estado.getTipoAlarma()));
			startActivity(i);
			Toast.makeText(this, "Se encontro Alarma", Toast.LENGTH_LONG).show();	
			
		}
		
		return true;
	}
}
